


package ciicos.controller;

import ciicos.model.lineplace.LinePlaceImagesModel;
import ciicos.service.LineLineService;
import ciicos.service.LinePlaceService;
import ciicos.util.convert.DataDicConvert;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ciicos.annotation.JnpfField;
import ciicos.base.ActionResult;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.base.UserInfo;
import ciicos.base.vo.DownloadVO;
import ciicos.config.ConfigValueUtil;
import ciicos.exception.DataException;
import ciicos.onlinedev.model.OnlineImport.ExcelImFieldModel;
import ciicos.onlinedev.model.OnlineImport.ExcelImportModel;
import ciicos.onlinedev.model.OnlineImport.VisualImportModel;
import ciicos.permission.entity.UserEntity;
import org.springframework.transaction.annotation.Transactional;
import ciicos.base.entity.ProvinceEntity;
import ciicos.model.linemaintain.*;
import ciicos.model.linemaintain.LineMaintainPagination;
import ciicos.entity.*;
import ciicos.entity.LineMaintainRecordEntity;
import ciicos.util.*;
import ciicos.base.util.*;
import ciicos.base.vo.ListVO;
import ciicos.util.context.SpringContext;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.Cleanup;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ciicos.entity.LineMaintainEntity;
import ciicos.service.LineMaintainService;
import ciicos.entity.LineMaintainRecordEntity;
import ciicos.service.LineMaintainRecordService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import ciicos.util.GeneraterSwapUtil;

import java.util.stream.Collectors;
import java.util.*;

import cn.xuyanwu.spring.file.storage.FileInfo;


/**
 * 管线维护管理
 *
 * @版本： V3.2.0
 * @版权：
 * @作者： 企业研发中心
 * @日期： 2025-10-06
 */
@Slf4j
@RestController
@Api(tags = "管线维护管理", value = "line")
@RequestMapping("/api/line/LineMaintain")
public class LineMaintainController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private LineMaintainService lineMaintainService;

    @Autowired
    private LineMaintainRecordService lineMaintainRecordService;

    @Autowired
    private LineLineService lineLineService;

    @Autowired
    private LinePlaceService linePlaceService;


    /**
     * 列表
     *
     * @param lineMaintainPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody LineMaintainPagination lineMaintainPagination) throws IOException {
        PageListVO vo = new PageListVO();

        //1.获取主表数据
        List<LineMaintainEntity> list = lineMaintainService.getList(lineMaintainPagination);
        if(list==null || list.size()==0){
            PaginationVO page = JsonUtil.getJsonToBean(lineMaintainPagination, PaginationVO.class);
            vo.setPagination(page);
            vo.setList(new ArrayList());
            return ActionResult.success(vo);
        }

        //2.获取字表数据
        //2.1获取所有的id
        List<String> parentIdList = list.stream().map(LineMaintainEntity::getId).collect(Collectors.toList());
        //2.2根据id查询字表
        List<LineMaintainRecordEntity> subEntityList = lineMaintainService.getLineMaintainRecordListByIdList(parentIdList);

        //3.字表数据按照id分组,同时转换为输出格式
        Map<String,List<LineMaintainRecordModel>> subModelMapList = new HashMap<>();
        if(ListUtil.isNotEmpty(subEntityList)) {
            //3.2遍历子表,
            for (LineMaintainRecordEntity entity : subEntityList) {
                String parentId = entity.getMaintainid();
                //转换为输出格式
                LineMaintainRecordModel model = JsonUtil.getJsonToBean(entity, LineMaintainRecordModel.class);
                subModelMapList.computeIfAbsent(parentId, k -> new ArrayList<>()).add(model);
            }
        }

        Map<String,String> mapList1 =
                AutoCodeUtil.getMapByCodeList(lineLineService,
                        list.stream().filter(t->StringUtil.equals(t.getLineplacetype(),"1")).map(LineMaintainEntity::getLineplaceid).collect(Collectors.toList()),
                        LineLineEntity::getCode,LineLineEntity::getName,true);
        Map<String,String> mapList2 =
                AutoCodeUtil.getMapByCodeList(linePlaceService,
                        list.stream().filter(t->StringUtil.equals(t.getLineplacetype(),"2")).map(LineMaintainEntity::getLineplaceid).collect(Collectors.toList()),
                        LinePlaceEntity::getCode,LinePlaceEntity::getName,true);

        //3.转为输出格式
        List<LineMaintainListVO> listVO = JsonUtil.getJsonToList(list, LineMaintainListVO.class);
        for (LineMaintainListVO lineMaintainVO : listVO) {
            lineMaintainVO.setLineplacetype_name(lineMaintainVO.getLineplacetype());

            if (lineMaintainVO.getLineplacetype().equals("1")) {
                lineMaintainVO.setLineplaceid_name(mapList1.get(lineMaintainVO.getLineplaceid()));
            } else if (lineMaintainVO.getLineplacetype().equals("2")) {
                lineMaintainVO.setLineplaceid_name(mapList2.get(lineMaintainVO.getLineplaceid()));
            }
            lineMaintainVO.setName_name(lineMaintainVO.getName());
            lineMaintainVO.setType_name(lineMaintainVO.getType());
            lineMaintainVO.setStarttime_name(lineMaintainVO.getStarttime() != null ?
                    new Date(lineMaintainVO.getStarttime()) : null);
            lineMaintainVO.setEndtime_name(lineMaintainVO.getEndtime() != null ?
                    new Date(lineMaintainVO.getEndtime()) : null);
            lineMaintainVO.setOrganizeid_name(generaterSwapUtil.comSelectValues(lineMaintainVO.getOrganizeid(), false));
            lineMaintainVO.setMasteruserid_name(generaterSwapUtil.userSelectValues(lineMaintainVO.getMasteruserid()));
            lineMaintainVO.setContactuserid_name(generaterSwapUtil.userSelectValues(lineMaintainVO.getContactuserid()));
            lineMaintainVO.setStatus_name(lineMaintainVO.getStatus());
            lineMaintainVO.setContent_name(lineMaintainVO.getContent());
            //插入子表数据
            lineMaintainVO.setLineMaintainRecordList(subModelMapList.get(lineMaintainVO.getId()));
        }


        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(lineMaintainPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param lineMaintainForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid LineMaintainForm lineMaintainForm) throws DataException {
        String b = lineMaintainService.checkForm(lineMaintainForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        LineMaintainEntity entity = JsonUtil.getJsonToBean(lineMaintainForm, LineMaintainEntity.class);
        entity.setId(mainId);
        lineMaintainService.save(entity);
        if (lineMaintainForm.getLinemaintainrecordList() != null) {
            List<LineMaintainRecordEntity> LineMaintainRecordList = JsonUtil.getJsonToList(lineMaintainForm.getLinemaintainrecordList(), LineMaintainRecordEntity.class);
            for (LineMaintainRecordEntity entitys : LineMaintainRecordList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setMaintainid(entity.getId());

                lineMaintainRecordService.save(entitys);
            }
        }


        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<LineMaintainInfoVO> info(@PathVariable("id") String id) {
        LineMaintainEntity entity = lineMaintainService.getInfo(id);
        LineMaintainInfoVO vo = JsonUtil.getJsonToBean(entity, LineMaintainInfoVO.class);

        //子表
        List<LineMaintainRecordEntity> LineMaintainRecordList = lineMaintainService.getLineMaintainRecordList(id);
        for (LineMaintainRecordEntity linemaintainrecordEntity : LineMaintainRecordList) {
        }
        vo.setLineMaintainRecordList(JsonUtil.getJsonToList(LineMaintainRecordList, LineMaintainRecordModel.class));
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<LineMaintainInfoVO> detailInfo(@PathVariable("id") String id) {
        ActionResult info = info(id);
        Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
        LineMaintainEntity entity = lineMaintainService.getInfo(id);
        LineMaintainInfoVO vo = JsonUtil.getJsonToBean(entity, LineMaintainInfoVO.class);

        //子表数据转换
        List<LineMaintainRecordEntity> lineMaintainRecordList = lineMaintainService.getLineMaintainRecordList(id);
        List<LineMaintainRecordModel> lineMaintainRecordModelList = JsonUtil.getJsonToList(lineMaintainRecordList, LineMaintainRecordModel.class);
        int lineMaintainRecordNum = 0;
        for (LineMaintainRecordModel lineMaintainRecordModel : lineMaintainRecordModelList) {
            lineMaintainRecordNum++;
        }
        vo.setLineMaintainRecordList(lineMaintainRecordModelList);

        //附表数据转换

//添加到详情表单对象中
        vo.setLineplacetype(vo.getLineplacetype());

        Map<String, Object> lineplaceidMap = new HashMap<>();
        vo.setLineplaceid(generaterSwapUtil.getPopupSelectValue("743867011288793541", "F_Code", "F_Code", vo.getLineplaceid(), lineplaceidMap, "[]", -1, dataMap));

        vo.setName(vo.getName());

        vo.setType(vo.getType());

        vo.setStarttime(vo.getStarttime());

        vo.setEndtime(vo.getEndtime());

        vo.setOrganizeid(generaterSwapUtil.comSelectValues(vo.getOrganizeid(), false));

        vo.setMasteruserid(generaterSwapUtil.userSelectValues(vo.getMasteruserid()));

        vo.setContactuserid(generaterSwapUtil.userSelectValues(vo.getContactuserid()));

        vo.setStatus(vo.getStatus());

        vo.setContent(vo.getContent());


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param lineMaintainForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid LineMaintainForm lineMaintainForm) throws DataException {
        String b = lineMaintainService.checkForm(lineMaintainForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        UserInfo userInfo = userProvider.get();
        LineMaintainEntity entity = lineMaintainService.getInfo(id);
        if (entity != null) {
            LineMaintainEntity subentity = JsonUtil.getJsonToBean(lineMaintainForm, LineMaintainEntity.class);
            boolean b1 = lineMaintainService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            QueryWrapper<LineMaintainRecordEntity> LineMaintainRecordqueryWrapper = new QueryWrapper<>();
            LineMaintainRecordqueryWrapper.lambda().eq(LineMaintainRecordEntity::getMaintainid, entity.getId());
            lineMaintainRecordService.remove(LineMaintainRecordqueryWrapper);
            if (lineMaintainForm.getLinemaintainrecordList() != null) {
                List<LineMaintainRecordEntity> LineMaintainRecordList = JsonUtil.getJsonToList(lineMaintainForm.getLinemaintainrecordList(), LineMaintainRecordEntity.class);
                for (LineMaintainRecordEntity entitys : LineMaintainRecordList) {

                    entitys.setId(RandomUtil.uuId());
                    entitys.setMaintainid(entity.getId());
                    lineMaintainRecordService.save(entitys);
                }
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        LineMaintainEntity entity = lineMaintainService.getInfo(id);
        if (entity != null) {
            lineMaintainService.delete(entity);
            QueryWrapper<LineMaintainRecordEntity> queryWrapperLineMaintainRecord = new QueryWrapper<>();
            queryWrapperLineMaintainRecord.lambda().eq(LineMaintainRecordEntity::getMaintainid, entity.getId());

            lineMaintainRecordService.remove(queryWrapperLineMaintainRecord);
        }
        return ActionResult.success("删除成功");
    }


}
